#include <Windows.h>
#include "Game.h"
#include "..//Timer.h"
#include "..//Renderer/Renderer.h"

//	States
#include "..//State System/GamePlayState.h"

CGame * CGame::GetInstance()
{
	static CGame instance;
	return &instance;
}

CGame::CGame( void )
{
	m_pRenderer = nullptr;
}

bool CGame::Input(void)
{
	return true;
}

void CGame::Update( )
{
	//	Update timer
	float fElapsedTime = m_Timer.GetDeltaTime();
	m_Timer.Update();
	m_vStates.back()->Update( fElapsedTime );
	Render(fElapsedTime);
}

void CGame::Render(float fElapsedTime)
{
	//	If the Renderer is already created
	//	or not corrupted
	if( m_pRenderer != nullptr )
	{
		//	Render every object in the game.
		m_pRenderer->RenderObjects(fElapsedTime);
	}
}

//Sets up the game
void CGame::Initialize( HWND hWnd, HINSTANCE hInstance, int nScreenWidth, 
		int nScreenHeight, bool bIsWindowed )
{
	m_nWindowWidth = nScreenWidth;
	m_nWindowHeight = nScreenHeight;
	m_bWindowMode = bIsWindowed;

	//m_hwndGame = hWnd;

	m_Timer.Reset();

	//	Init the Render singleton
	m_pRenderer = CRenderer::GetInstance();
	m_pRenderer->Initialize( hWnd, nScreenWidth, nScreenHeight, bIsWindowed);

	PushState( CGameplayState::GetInstance() );
}

bool CGame::LogicLoop( void )
{
	if( m_vStates.size() == 0 || Input() == false)
		return false;
	Update();

	return true;	
}

void CGame::PushState(IGameState* pNewState, bool bExitState )
{
	if( m_vStates.size() > 0 )
	{
		if( bExitState == true )
			m_vStates.back()->Exit();
	}

	m_vStates.push_back( pNewState );

	if( m_vStates.size() > 0 )
	{
		m_vStates.back()->Enter();
	}
}

void CGame::PopState( bool bEnterState )
{
	if( m_vStates.size() > 0 )
	{
		m_vStates.back()->Exit();
		m_vStates.pop_back();
	}

	if( m_vStates.back() > 0 )
	{
		if( bEnterState == true )
			m_vStates.back()->Enter();
	}
}

//Cleans up any needed memory
void CGame::Shutdown(void)
{
	while (m_vStates.size() > 0)
	{
		if( m_vStates[m_vStates.size()-1] != nullptr )
			m_vStates[m_vStates.size()-1]->Exit();

		m_vStates.pop_back();
	}
	m_vStates.clear();

	// Shutdown the Renderer
	m_pRenderer->Shutdown();

	//	Delete any allocated memory!

	/*if( Instance != nullptr )
		delete Instance;*/


	//Instance = nullptr;
}
